package com.addplus.townmall.server.api.utils;

import com.addplus.townmall.server.api.model.town.Area;
import com.addplus.townmall.server.api.model.town.expand.AreaExpand;
import org.springframework.beans.BeanUtils;

import java.util.*;

public class AreaTreeUtils {
    public static List<AreaExpand> getAreaTree(List<Area> areas) {
        if (areas != null && !areas.isEmpty()) {
            List<Integer> idList = new ArrayList<Integer>();
            HashMap<Integer, AreaExpand> hashMap = new HashMap<Integer, AreaExpand>();
            AreaExpand areaExpand = null;
            for (Area area : areas) {
                areaExpand = new AreaExpand();
                BeanUtils.copyProperties(area, areaExpand, Area.class);
                hashMap.put(area.getId(), areaExpand);
                idList.add(area.getId());
            }
            for (Integer num : idList) {
                areaExpand = hashMap.get(num);
                if (hashMap.containsKey(areaExpand.getPid())) {
                    AreaExpand areaFather = hashMap.get(areaExpand.getPid());
                    List<AreaExpand> areaChirldrenList = null;
                    if (areaFather.getAreaList()!= null && !areaFather.getAreaList().isEmpty()) {
                        areaChirldrenList = areaFather.getAreaList();
                    } else {
                        areaChirldrenList = new ArrayList<AreaExpand>();
                    }
                    areaChirldrenList.add(areaExpand);
                    areaFather.setAreaList(areaChirldrenList);
                    hashMap.put(areaFather.getId(), areaFather);
                    hashMap.remove(areaExpand.getId());
                }
            }
            List<AreaExpand> areaTree = new ArrayList<AreaExpand>();
            for (Map.Entry<Integer, AreaExpand> o : hashMap.entrySet()) {
                areaTree.add(o.getValue());
            }
            if (areaTree != null && !areaTree.isEmpty()) {
                Collections.sort(areaTree);
                //进行排序
                for (AreaExpand area : areaTree) {
                    List<AreaExpand> areaChildrenList = area.getAreaList();
                    if (areaChildrenList != null && !areaChildrenList.isEmpty()) {
                        Collections.sort(areaChildrenList);
                    }
                }
                return areaTree;
            }
        }
        return null;
    }
}
